from datetime import datetime
from typing import Optional
from uuid import UUID, uuid4

from bisheng.database.base import session_getter
from bisheng.database.models.base import SQLModelSerializable
from sqlalchemy import Column, DateTime, String, Text, text
from sqlmodel import Field, select


class RequestRecordBase(SQLModelSerializable):
    id: UUID = Field(nullable=False, primary_key=True, description='唯一ID')
    request_body: str = Field(sa_column=Column(Text), default="", description='请求内容')
    request_url: str = Field(sa_column=Column(String(length=255), default=''), description='请求地址')
    request_method: str = Field(sa_column=Column(String(length=255), default=''), description='请求方法')
    response_body: str = Field(sa_column=Column(Text), default="", description='响应内容')
    response_code: str = Field(sa_column=Column(String(length=255), default=''), description='检修周期')
    response_time: Optional[datetime] = Field(sa_column=Column(DateTime), description='请求时间')
    create_time: Optional[datetime] = Field(
        sa_column=Column(DateTime, nullable=False, server_default=text('CURRENT_TIMESTAMP')))
    update_time: Optional[datetime] = Field(sa_column=Column(DateTime,
                                                             nullable=False,
                                                             index=True,
                                                             server_default=text('CURRENT_TIMESTAMP'),
                                                             onupdate=text('CURRENT_TIMESTAMP')))


class RequestRecord(RequestRecordBase, table=True):
    id: UUID = Field(default_factory=uuid4, primary_key=True, unique=True)


class RequestRecordDao:
    @staticmethod
    def create_request_record(request_record: RequestRecord) -> RequestRecord:
        """
        创建新的请求记录

        :param request_record: RequestRecord 对象
        :return: 创建并保存到数据库的 RequestRecord 对象
        """
        with session_getter() as session:
            # 确保 request_record 有一个 UUID
            if not request_record.id:
                request_record.id = uuid4()

            # 如果没有提供 response_time，设置为当前时间
            if not request_record.response_time:
                request_record.response_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')

            session.add(request_record)
            session.commit()
            session.refresh(request_record)
            return request_record
